//
//  YXJPushMusicViewController.m
//  Piece
//
//  Created by dllo on 16/6/18.
//  Copyright © 2016年 Northeast Dianli University. All rights reserved.
//

#import "YXJPushMusicViewController.h"
#import "YXJView.h"
#import "YXJMusicModel.h"
#import "YXJMusicStoryCell.h"
#import "YXJListCell.h"
#import "YXJContentModel.h"
#import "YXJCommentCell.h"
#import "YXJMusicCell.h"
#import "YXJLikeMusicModel.h"
#import "YXJLikeMusicCell.h"
#import "ZHNetworkHandler.h"
#import "UIImageView+WebCache.h"
#import "AppDelegate.h"


@interface YXJPushMusicViewController ()<UITableViewDelegate, UITableViewDataSource, MusicPlayDelegate>

@property (nonatomic, strong) UITableView *tableView;

/** 音乐的头视图 */
@property (nonatomic, strong) UIView *headView;

/** 音乐的播放图片 */
@property (nonatomic, strong) UIImageView *photoImageView;

/** 音乐的信息视图 */
@property (nonatomic, strong) YXJView *contentView;

/** 初始化音乐故事 */
@property (nonatomic, strong) UILabel *musicStoryLabel;

/** 初始化音乐故事按钮 */
@property (nonatomic, strong) UIButton *storyButton;

/** 初始化歌词按钮 */
@property (nonatomic, strong) UIButton *lyricButton;

/** 初始化歌曲信息按钮 */
@property (nonatomic, strong) UIButton *aboutButton;

@property (nonatomic, strong) YXJMusicModel *model;

@property (nonatomic, strong) YXJMusicStoryCell *musicStoryCell;

/** 初始化评论列表 */
@property (nonatomic, strong) YXJListCell *listCell;

@property (nonatomic, strong) YXJContentModel *contentModel;

@property (nonatomic, strong) YXJCommentCell *commentCell;

@property (nonatomic, strong) NSMutableArray *contentDataSource;

/** 初始化相似歌曲 */
@property (nonatomic, strong) YXJLikeMusicCell *likeMusiCell;

@property (nonatomic, strong) YXJMusicCell *musicCell;

@property (nonatomic, strong) YXJLikeMusicModel *likeMusicModel;

@property (nonatomic, strong) NSMutableArray *likeMusicDataSource;

/** 点击区分cell的属性 */
@property (nonatomic, assign) NSInteger whichPage;

@property (nonatomic, strong) NSMutableArray *commentDataSoucre;

/** 网络数据model */
@property (nonatomic, strong) YXJMusicModel *musicModel;

@property (nonatomic, assign) NSInteger pageId;

@end

@implementation YXJPushMusicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self creatTableView];
    
    if (self.pageS != 0) {
        
        [self getDataByIdNumber:self.pageS];
        [self getCommentDataByIdNumber:self.pageS];
        
    }else if (self.pageSSSS != 0){
        
        [self getDataByIdNumber:self.pageSSSS];
        [self getCommentDataByIdNumber:self.pageSSSS];
    }
    {
        
    [self getDataByIdNumber:self.pageID];
    [self getCommentDataByIdNumber:self.pageID];
    }
}
- (void)creatTableView
{
    //初始化tableView
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 113) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = 0;
    [self.tableView setContentOffset:CGPointMake(0, 180)];
    [self.view addSubview:_tableView];
    
    [self.tableView registerClass:[YXJMusicStoryCell class] forCellReuseIdentifier:@"musicStroyCell"];
    [self.tableView registerClass:[YXJListCell class] forCellReuseIdentifier:@"listCell"];
    [self.tableView registerClass:[YXJCommentCell class] forCellReuseIdentifier:@"commentCell"];
    [self.tableView registerClass:[YXJMusicCell class] forCellReuseIdentifier:@"musicCell"];
    [self.tableView registerClass:[YXJLikeMusicCell class] forCellReuseIdentifier:@"likeMusicCell"];
    
    //初始化headView
    self.headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 143)];
    self.tableView.tableHeaderView = _headView;
    
    //初始化歌曲背景图片
    self.photoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth)];
    [self.photoImageView sd_setImageWithURL:[NSURL URLWithString:self.musicModel.cover]];
    [self.headView addSubview:_photoImageView];
    
    //初始化歌曲信息view
    self.contentView = [[YXJView alloc] initWithFrame:CGRectMake(10, ScreenWidth - 15, ScreenWidth - 20, 110)];
    self.contentView.backgroundColor = [UIColor whiteColor];
    self.contentView.layer.borderWidth = 2;
    self.contentView.layer.borderColor = [UIColor colorWithRed:0.87 green:0.87 blue:0.88 alpha:1.00].CGColor;
    self.contentView.delegate = self;
    [self.headView addSubview:_contentView];
    
    //初始化音乐故事
    self.musicStoryLabel = [[UILabel alloc] initWithFrame:CGRectMake(_contentView.frame.origin.x, ScreenWidth + _contentView.frame.size.height, 100, 20)];
    self.whichPage = 2;
    self.musicStoryLabel.text = @"歌词";
    [self.musicStoryLabel setTextColor:[UIColor colorWithRed:0.73 green:0.73 blue:0.74 alpha:1.00]];
    self.musicStoryLabel.font = [UIFont systemFontOfSize:13];
    [self.headView addSubview:_musicStoryLabel];
    
    //初始化歌词按钮
    self.lyricButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.lyricButton.frame = CGRectMake(ScreenWidth - 105, _musicStoryLabel.frame.origin.y, 44, 44);
    [_lyricButton addTarget:self action:@selector(didLyricButton:) forControlEvents:UIControlEventTouchUpInside];
    [_lyricButton setImage:[UIImage imageNamed:@"music_lyric_normal"] forState:UIControlStateNormal];
    _lyricButton.tag = 1002;
    [self.headView addSubview:_lyricButton];
    
    
    //初始化歌曲信息按钮
    self.aboutButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.aboutButton.frame = CGRectMake(ScreenWidth - 50, _musicStoryLabel.frame.origin.y, 44, 44);
    [_aboutButton addTarget:self action:@selector(didAboutButton:) forControlEvents:UIControlEventTouchUpInside];
    [_aboutButton setImage:[UIImage imageNamed:@"music_about_normal"] forState:UIControlStateNormal];
    _aboutButton.tag = 1003;
    [self.headView addSubview:_aboutButton];
    
}
#pragma mark -- 播放音乐代理方法
- (void)musicPlay
{
    
    AppDelegate *appDelegate = [AppDelegate shareDetailViewController];
    appDelegate.musicInfo = _musicModel;
    
//    [[XZHMusicPlayView shareMusicPlayViewInstance] setIndex:_pageNumber];
//    [[XZHMusicPlayView shareMusicPlayViewInstance] setMusicArr:_idListDataSource];
    [[XZHMusicPlayView shareMusicPlayViewInstance] setIsPlay:YES];
    [[[XZHMusicPlayView shareMusicPlayViewInstance] pauseButton] setHidden:NO];
    [[[XZHMusicPlayView shareMusicPlayViewInstance] playButton] setHidden:YES];
    [[[XZHMusicPlayView shareMusicPlayViewInstance] titleLabel] setText:_musicModel.title];
    [[[XZHMusicPlayView shareMusicPlayViewInstance] titleLabel] setFont:[UIFont systemFontOfSize:17]];
}

#pragma mark -- button的点击方法

- (void)didLyricButton:(UIButton *)sender
{
    self.musicStoryLabel.text = @"歌词";
    [sender setImage:[UIImage imageNamed:@"music_lyric_selected"] forState:UIControlStateNormal];
    [_storyButton setImage:[UIImage imageNamed:@"music_story_normal"] forState:UIControlStateNormal];
    [_aboutButton setImage:[UIImage imageNamed:@"music_about_normal"] forState:UIControlStateNormal];
    self.whichPage = 2;
    [self.tableView reloadData];
}

- (void)didAboutButton:(UIButton *)sender
{
    self.musicStoryLabel.text = @"相关信息";
    [sender setImage:[UIImage imageNamed:@"music_about_selected"] forState:UIControlStateNormal];
    [_storyButton setImage:[UIImage imageNamed:@"music_story_normal"] forState:UIControlStateNormal];
    [_lyricButton setImage:[UIImage imageNamed:@"music_lyric_normal"] forState:UIControlStateNormal];
    self.whichPage = 3;
    [self.tableView reloadData];
}

#pragma mark -- 网络解析(获取头视图)
- (void)getDataByIdNumber:(NSInteger)idNumber
{
    NSString *urlString = [NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/music/detail/%ld", idNumber];
    [ZHNetworkHandler getDataByURLString:urlString WithBodyString:nil WithHeaderDic:nil WithResponse:ZHJSON WithSuccess:^(id result) {
        
        NSDictionary *diction = [result objectForKey:@"data"];
        
        self.musicModel = [[YXJMusicModel alloc] initWithDic:diction];
        
        [self.tableView reloadData];
    }
    
    WithFailure:^(NSError *error) {
        
    }];
}

#pragma mark -- 网络解析(获取评论数据)
- (void)getCommentDataByIdNumber:(NSInteger)idNumber
{
    self.commentDataSoucre = [NSMutableArray array];
    
    NSString *commentString = [NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/comment/praise/music/%ld/0", idNumber];
    
    [ZHNetworkHandler getDataByURLString:commentString WithBodyString:nil WithHeaderDic:nil WithResponse:ZHJSON WithSuccess:^(id result) {
        
        NSDictionary *diction = [result objectForKey:@"data"];
        
        NSArray *array = [diction objectForKey:@"data"];
        
        for (NSDictionary *dic in array) {
            
            YXJContentModel *model = [[YXJContentModel alloc] initWithDic:dic];
            
            [self.commentDataSoucre addObject:model];
        }
        YXJContentModel *nilModel = [[YXJContentModel alloc] init];
        [self.commentDataSoucre insertObject:nilModel atIndex:0];
        
        [self.tableView reloadData];
        
    } WithFailure:^(NSError *error) {
        
    }];
}



#pragma mark -- tableView的协议方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    else {
        return 0;
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (self.whichPage == 2) {
            NSString *str = self.model.lyric;
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:13], NSFontAttributeName, nil];
            CGRect newRect = [str boundingRectWithSize:CGSizeMake(ScreenWidth - 20, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
            return newRect.size.height + 500;
        }
        
        if (self.whichPage == 3) {
            NSString *str = self.model.info;
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:13], NSFontAttributeName, nil];
            CGRect newRect = [str boundingRectWithSize:CGSizeMake(ScreenWidth - 20, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
            return newRect.size.height + 250;
        }
        
        
        
    }
    
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            return 40;
        }  else  {
            if (self.commentDataSoucre.count != 0) {
                NSString *str = [[self.commentDataSoucre objectAtIndex:indexPath.row] content];
                NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:13], NSFontAttributeName, nil];
                CGRect newRect = [str boundingRectWithSize:CGSizeMake(ScreenWidth - 20, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
                return newRect.size.height + 130;
            }
        }
    }
    return 0;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    __weak YXJPushMusicViewController *pMVC = self;
    _contentView.clickBlock = ^(){
        [[NSNotificationCenter defaultCenter] postNotificationName:@"play" object:[NSString stringWithFormat:@"%ld", pMVC.musicModel.platform]];
        if (self.musicModel.platform == 1) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"该首歌曲由于版权暂时无法播放" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alert addAction:action];
            [pMVC presentViewController:alert animated:YES completion:nil];
        }
    };
    if (indexPath.section == 0) {
        
        YXJMusicStoryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"musicStroyCell"];
        cell.page = self.whichPage;
        cell.model = self.musicModel;
        [self.photoImageView sd_setImageWithURL:[NSURL URLWithString:self.musicModel.cover]];
        [self.contentView.userImageView sd_setImageWithURL:[NSURL URLWithString:self.musicModel.authorModel.web_url]];
        self.contentView.realName.text = self.musicModel.authorModel.user_name;
        self.contentView.nickName.text = self.musicModel.authorModel.desc;
        self.contentView.musicName.text = self.musicModel.title;
        self.contentView.dateLabel.text = [self changeFormString:self.musicModel.maketime];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            YXJListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"listCell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
        if (indexPath.row != 0) {
            YXJCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentCell"];
            cell.contentModel = [self.commentDataSoucre objectAtIndex:indexPath.row];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    }
    return nil;
}


- (NSString *)changeFormString:(NSString *)string
{
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:@"yy-MM-dd HH:mm:ss"];//yyyyMMddHHmmss
    
    NSDate *inputDate = [inputFormatter dateFromString:string];
    
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [outputFormatter setDateFormat:@"MMM.dd.yyyy"];
    
    NSString *outputDate = [outputFormatter stringFromDate:inputDate];
    return outputDate;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
